
/* Base on FreeRTOS MemMang heap_4.c
 * Port by shengda.huang @ 2020/6/29
 */

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include "heap.h"

#define heap_log(_fmt_, ...) \
		printf("[HP][%s:%d][%s] "_fmt_"\r\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)

/* Block sizes must not get too small. */
#define heapMINIMUM_BLOCK_SIZE	( ( size_t ) ( _this->xHeapStructSize * 2 ) )

/* Assumes 8bit bytes! */
#define heapBITS_PER_BYTE		( ( size_t ) 8 )

#define heap4_assert( x ) do { \
							if (!(x)) \
								while (1) \
									heap_log("assert(%s)", #x); \
						  } while (0)

#ifndef heap4_trace_malloc
    #define heap4_trace_malloc( pvAddress, uiSize )
#endif

#ifndef heap4_trace_free
    #define heap4_trace_free( pvAddress, uiSize )
#endif

#ifndef heap4_spin_lock
	#define heap4_spin_lock()
#endif

#ifndef heap4_spin_unlock
	#define heap4_spin_unlock()
#endif

/* Define the linked list structure.  This is used to link free blocks in order
of their memory address. */
typedef struct A_BLOCK_LINK
{
	struct A_BLOCK_LINK *pxNextFreeBlock;	/*<< The next free block in the list. */
	size_t xBlockSize;						/*<< The size of the free block. */
} BlockLink_t;

/*-----------------------------------------------------------*/

struct heap_mgr {
	/* Create a couple of list links to mark the start and end of the list. */
	BlockLink_t xStart;
	BlockLink_t *pxEnd;

	/* The size of the structure placed at the beginning of each allocated memory
	 * block must by correctly byte aligned. */
	size_t xHeapStructSize;

	/* Keeps track of the number of free bytes remaining, but says nothing about
	 * fragmentation. */
	size_t xFreeBytesRemaining;
	size_t xMinimumEverFreeBytesRemaining;

	/* Gets set to the top bit of an size_t type.  When this bit in the xBlockSize
	 * member of an BlockLink_t structure is set then the block belongs to the
	 * application.  When the bit is free the block is still part of the free heap
	 * space. */
	size_t xBlockAllocatedBit;
	
	unsigned int poolsize;
	uint8_t heap_pool[0];
};
/*-----------------------------------------------------------*/

/*
 * Inserts a block of memory that is being freed into the correct position in
 * the list of free memory blocks.  The block being freed will be merged with
 * the block in front it and/or the block behind it if the memory blocks are
 * adjacent to each other.
 */
static void prvInsertBlockIntoFreeList(struct heap_mgr *_this, BlockLink_t *pxBlockToInsert);

/*-----------------------------------------------------------*/

void heap4_blocklink_info(heap_hdl_t heap, const char *str)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	BlockLink_t *pxBlock;

	heap_log("%s", str);

	pxBlock = &_this->xStart;
	do {
		heap_log("pxBlock %p xBlockSize %d pxNextFreeBlock %p", pxBlock, \
				 pxBlock->xBlockSize, pxBlock->pxNextFreeBlock);
		pxBlock = pxBlock->pxNextFreeBlock;
	} while( pxBlock != NULL );
}

void *heap4_malloc(heap_hdl_t heap, size_t xWantedSize)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
	void *pvReturn = NULL;

	heap4_spin_lock();
	if( _this->pxEnd != NULL )
	{
		/* Check the requested block size is not so large that the top bit is
		set.  The top bit of the block size member of the BlockLink_t structure
		is used to determine who owns the block - the application or the
		kernel, so it must be free. */
		if( ( xWantedSize & _this->xBlockAllocatedBit ) == 0 )
		{
			/* The wanted size is increased so it can contain a BlockLink_t
			structure in addition to the requested amount of bytes. */
			if( xWantedSize > 0 )
			{
				heap_log("xWantedSize %d", xWantedSize);
				xWantedSize += _this->xHeapStructSize;
				heap_log("xWantedSize %d", xWantedSize);

				/* Ensure that blocks are always aligned to the required number
				of bytes. */
				if( ( xWantedSize & HEAP4_BYTE_ALIGNMENT_MASK ) != 0x00 )
				{
					/* Byte alignment required. */
					xWantedSize += ( HEAP4_BYTE_ALIGNMENT - ( xWantedSize & HEAP4_BYTE_ALIGNMENT_MASK ) );
					heap_log("xWantedSize %d", xWantedSize);
					heap4_assert( ( xWantedSize & HEAP4_BYTE_ALIGNMENT_MASK ) == 0 );
				}
			}

			heap_log("xWantedSize %d xFreeBytesRemaining %d", xWantedSize, _this->xFreeBytesRemaining);
			if( ( xWantedSize > 0 ) && ( xWantedSize <= _this->xFreeBytesRemaining ) )
			{
				/* Traverse the list from the start	(lowest address) block until
				one	of adequate size is found. */
				pxPreviousBlock = &_this->xStart;
				pxBlock = _this->xStart.pxNextFreeBlock;
				while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
				{
					pxPreviousBlock = pxBlock;
					pxBlock = pxBlock->pxNextFreeBlock;
				}

				/* If the end marker was reached then a block of adequate size
				was	not found. */
				heap_log("pxBlock %p pxEnd %p", pxBlock, _this->pxEnd);
				if( pxBlock != _this->pxEnd )
				{
					/* Return the memory space pointed to - jumping over the
					BlockLink_t structure at its start. */
					pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + _this->xHeapStructSize );

					/* This block is being returned for use so must be taken out
					of the list of free blocks. */
					pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;

					/* If the block is larger than required it can be split into
					two. */
					if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
					{
						/* This block is to be split into two.  Create a new
						block following the number of bytes requested. The void
						cast is used to prevent byte alignment warnings from the
						compiler. */
						pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
						heap4_assert( ( ( ( uint32_t ) pxNewBlockLink ) & HEAP4_BYTE_ALIGNMENT_MASK ) == 0 );

						/* Calculate the sizes of two blocks split from the
						single block. */
						pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
						pxBlock->xBlockSize = xWantedSize;

						/* Insert the new block into the list of free blocks. */
						prvInsertBlockIntoFreeList(_this, ( pxNewBlockLink ));
					}

					_this->xFreeBytesRemaining -= pxBlock->xBlockSize;

					if( _this->xFreeBytesRemaining < _this->xMinimumEverFreeBytesRemaining )
					{
						_this->xMinimumEverFreeBytesRemaining = _this->xFreeBytesRemaining;
					}

					/* The block is being returned - it is allocated and owned
					by the application and has no "next" block. */
					pxBlock->xBlockSize |= _this->xBlockAllocatedBit;
					pxBlock->pxNextFreeBlock = NULL;
				}
			}
		}

		heap4_trace_malloc( pvReturn, xWantedSize );
	}
	heap4_spin_unlock();

	heap4_blocklink_info(_this, "final of heap4_malloc");

	heap4_assert( ( ( ( uint32_t ) pvReturn ) & HEAP4_BYTE_ALIGNMENT_MASK ) == 0 );
	return pvReturn;
}
/*-----------------------------------------------------------*/

static void __vPortFree(struct heap_mgr *_this, void *pv)
{
	uint8_t *puc = ( uint8_t * ) pv;
	BlockLink_t *pxLink;

	if( pv != NULL )
	{
		/* The memory being freed will have an BlockLink_t structure immediately
		before it. */
		puc -= _this->xHeapStructSize;

		/* This casting is to keep the compiler from issuing warnings. */
		pxLink = ( void * ) puc;

		/* Check the block is actually allocated. */
		heap4_assert( ( pxLink->xBlockSize & _this->xBlockAllocatedBit ) != 0 );
		heap4_assert( pxLink->pxNextFreeBlock == NULL );

		if( ( pxLink->xBlockSize & _this->xBlockAllocatedBit ) != 0 )
		{
			if( pxLink->pxNextFreeBlock == NULL )
			{
				/* The block is being returned to the heap - it is no longer
				allocated. */
				pxLink->xBlockSize &= ~_this->xBlockAllocatedBit;

				heap4_spin_lock();
				{
					/* Add this block to the list of free blocks. */
					_this->xFreeBytesRemaining += pxLink->xBlockSize;
					heap4_trace_free( pv, pxLink->xBlockSize );
					prvInsertBlockIntoFreeList(_this, ( ( BlockLink_t * ) pxLink ));
				}
				heap4_spin_unlock();
			}
		}
	}
}
/*-----------------------------------------------------------*/

void heap4_free(heap_hdl_t heap, void *pv)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	__vPortFree(_this, pv);

	heap4_blocklink_info(_this, "final of heap4_free");
}

/*-----------------------------------------------------------*/

size_t heap4_freeheapsize(heap_hdl_t heap)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	return _this->xFreeBytesRemaining;
}
/*-----------------------------------------------------------*/

size_t heap4_mineverfreeheapsize(heap_hdl_t heap)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	return _this->xMinimumEverFreeBytesRemaining;
}

/*-----------------------------------------------------------*/

void heap4_init(heap_hdl_t heap, unsigned int size)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	BlockLink_t *pxFirstFreeBlock;
	uint8_t *pucAlignedHeap;
	uint32_t ulAddress;
	size_t xTotalHeapSize;

	heap_log("sizeof(struct heap_mgr) %d", sizeof(struct heap_mgr));
	heap_log("offsetof(struct heap_mgr, heap_pool) %d", offsetof(struct heap_mgr, heap_pool));

	_this->pxEnd = NULL;
	_this->xHeapStructSize = ( ( sizeof( BlockLink_t ) + ( HEAP4_BYTE_ALIGNMENT - 1 ) ) & ~HEAP4_BYTE_ALIGNMENT_MASK );
	_this->xFreeBytesRemaining = 0U;
	_this->xMinimumEverFreeBytesRemaining = 0U;
	_this->xBlockAllocatedBit = 0U;
	_this->poolsize = size - offsetof(struct heap_mgr, heap_pool);

	heap_log("xHeapStructSize %d poolsize %d", _this->xHeapStructSize, _this->poolsize);

	xTotalHeapSize = _this->poolsize;

	/* Ensure the heap starts on a correctly aligned boundary. */
	ulAddress = ( uint32_t ) _this->heap_pool;

	if( ( ulAddress & HEAP4_BYTE_ALIGNMENT_MASK ) != 0 )
	{
		ulAddress += ( HEAP4_BYTE_ALIGNMENT - 1 );
		ulAddress &= ~HEAP4_BYTE_ALIGNMENT_MASK;
		xTotalHeapSize -= ulAddress - ( uint32_t ) _this->heap_pool;
	}

	pucAlignedHeap = ( uint8_t * ) ulAddress;

	heap_log("_this->heap_pool %p ulAddress 0x%x pucAlignedHeap %p", _this->heap_pool, ulAddress, pucAlignedHeap);

	/* xStart is used to hold a pointer to the first item in the list of free
	blocks.  The void cast is used to prevent compiler warnings. */
	_this->xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
	_this->xStart.xBlockSize = ( size_t ) 0;

	/* pxEnd is used to mark the end of the list of free blocks and is inserted
	at the end of the heap space. */
	ulAddress = ( ( uint32_t ) pucAlignedHeap ) + xTotalHeapSize;
	ulAddress -= _this->xHeapStructSize;
	ulAddress &= ~HEAP4_BYTE_ALIGNMENT_MASK;
	_this->pxEnd = ( void * ) ulAddress;
	_this->pxEnd->xBlockSize = 0;
	_this->pxEnd->pxNextFreeBlock = NULL;

	/* To start with there is a single free block that is sized to take up the
	entire heap space, minus the space taken by pxEnd. */
	pxFirstFreeBlock = ( void * ) pucAlignedHeap;
	pxFirstFreeBlock->xBlockSize = ulAddress - ( uint32_t ) pxFirstFreeBlock;
	pxFirstFreeBlock->pxNextFreeBlock = _this->pxEnd;

	/* Only one block exists - and it covers the entire usable heap space. */
	_this->xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
	_this->xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;

	/* Work out the position of the top bit in a size_t variable. */
	_this->xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
	heap_log("heapBITS_PER_BYTE %x xBlockAllocatedBit %x xHeapStructSize %d", \
			 heapBITS_PER_BYTE, _this->xBlockAllocatedBit, _this->xHeapStructSize);

	heap4_blocklink_info(_this, "final of heap4_init");
}
/*-----------------------------------------------------------*/

static void prvInsertBlockIntoFreeList(struct heap_mgr *_this, BlockLink_t *pxBlockToInsert)
{
	BlockLink_t *pxIterator;
	uint8_t *puc;

	heap4_blocklink_info(_this, "begin of prvInsertBlockIntoFreeList");

	/* Iterate through the list until a block is found that has a higher address
	than the block being inserted. */
	for( pxIterator = &_this->xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
	{
		/* Nothing to do here, just iterate to the right position. */
		heap_log("pxBlockToInsert %p pxNextFreeBlock %p", pxBlockToInsert, pxIterator->pxNextFreeBlock);
	}
	heap_log("pxBlockToInsert %p pxNextFreeBlock %p", pxBlockToInsert, pxIterator->pxNextFreeBlock);

	/* Do the block being inserted, and the block it is being inserted after
	make a contiguous block of memory? */
	puc = ( uint8_t * ) pxIterator;
	if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
	{
		pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
		pxBlockToInsert = pxIterator;
	}

	/* Do the block being inserted, and the block it is being inserted before
	make a contiguous block of memory? */
	puc = ( uint8_t * ) pxBlockToInsert;
	if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
	{
		if( pxIterator->pxNextFreeBlock != _this->pxEnd )
		{
			/* Form one big block from the two blocks. */
			pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
			pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
		}
		else
		{
			pxBlockToInsert->pxNextFreeBlock = _this->pxEnd;
		}
	}
	else
	{
		pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
	}

	/* If the block being inserted plugged a gab, so was merged with the block
	before and the block after, then it's pxNextFreeBlock pointer will have
	already been set, and should not be set here as that would make it point
	to itself. */
	if( pxIterator != pxBlockToInsert )
	{
		pxIterator->pxNextFreeBlock = pxBlockToInsert;
	}
}
/*-----------------------------------------------------------*/

void* heap4_realloc(heap_hdl_t heap, void *pv, size_t xWantedSize)
{
	struct heap_mgr *_this = (struct heap_mgr *)heap;
	BlockLink_t *pxLink;
	unsigned char *puc = ( unsigned char * ) pv;

	if( pv )
	{
		if( !xWantedSize )
		{
			heap4_free(_this, pv);
			return NULL;
		}

		void *newArea = heap4_malloc(_this, xWantedSize);
		if( newArea )
		{
			/* The memory being freed will have an xBlockLink structure immediately
				before it. */
			puc -= _this->xHeapStructSize;

			/* This casting is to keep the compiler from issuing warnings. */
			pxLink = ( void * ) puc;

			int oldSize =  (pxLink->xBlockSize & ~_this->xBlockAllocatedBit) - _this->xHeapStructSize;
			int copySize = ( oldSize < xWantedSize ) ? oldSize : xWantedSize;
			memcpy( newArea, pv, copySize );

			heap4_spin_lock();
			{
				/* Add this block to the list of free blocks. */
				pxLink->xBlockSize &= ~_this->xBlockAllocatedBit;
				_this->xFreeBytesRemaining += pxLink->xBlockSize;
				prvInsertBlockIntoFreeList(_this, ( ( BlockLink_t * ) pxLink ));
			}
			heap4_spin_unlock();
			return newArea;
		}
	}
	else if( xWantedSize )
		return heap4_malloc(_this, xWantedSize);
	else
		return NULL;

	return NULL;
}

